<template>
  <div class="about">
    <div class="wrap">
      <h1>来说说你想做什么：</h1>
      昵称：<input type="text"
             v-model="nickname">
      <br>
      <div>
        <input type="text"
               class="msg"
               v-model="msg">
      </div>
      <div class="send_wrap">
        <span>还剩 <span>{{20-this.msg.length}}</span> 个字</span>
        <button @click="send()">广播</button>
      </div>
      <hr>
      <h1>大家在说：</h1>
      <div class="list">
        <div class="list_one"
             v-for="item in msgList"
             :key="item._id">
          <img src="../assets/logo.png"
               alt="">
          <div>
            <div>
              <span class="username">{{item.nickname}}</span> <span class="content">{{item.msg}}</span>
            </div>
            <div>{{new Date(item.time).toLocaleString()}}</div>
          </div>
          <button @click="del(item._id)">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { addMsg, MsgList, delMsg } from '../api/msg'
export default {
  data () {
    return {
      nickname: "", //昵称
      msg: "", //留言内容
      msgList: [],//留言数据
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 添加留言接口
    async send () {
      if (this.msg && this.nickname) {
        var res = await addMsg({ nickname: this.nickname, msg: this.msg })
        console.log(res)
        if (res.data.success) {
          this.getList();
          this.nickname = ""
          this.msg = ""
        }
      } else {
        alert("补全信息")
      }
    },
    // 获取留言列表
    async getList () {
      var res = await MsgList()
      console.log(res)
      this.msgList = res.data.data;
    },
    async del (id) {
      var res = await delMsg(id)
      if (res.data.success) {
        this.getList();
      }
    }
  },
  watch: {
    msg (newVal, oldVal) {
      if (newVal.length > 20) {
        this.msg = newVal.substr(0, 20)
      }
    }
  }
}
</script>
<style lang="less">
.wrap {
  width: 80%;
  margin: 20px auto;
  border: 2px solid red;
  .msg {
    width: 80%;
    height: 220px;
    margin: 20px auto;
  }
  .send_wrap {
    display: flex;
    justify-content: flex-end;
    padding: 0 50px;
    box-sizing: border-box;
    button {
      background: green;
      color: white;
      width: 110px;
    }
  }
  .list {
    .list_one {
      width: 80%;
      height: 120px;
      margin: 10px auto;
      background: skyblue;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .username {
        font-size: 20px;
      }
      .content {
        font-size: 25px;
      }
      img {
        width: 100px;
        height: 100px;
        margin: 10px;
      }
    }
  }
}
</style>
